package calcul;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JOptionPane;

public class Calculator {
	public ArrayList<Integer> getBaseAdress(ArrayList<Integer> ip,
			ArrayList<Integer> masc) throws Exception {
		String baseAdress = "";
		ArrayList<Integer> baseAdressArr = new ArrayList<Integer>();
		/** check if masc is in short form then transform in long form */

		BinaryTransform binarryTransformTest = new BinaryTransform();
		LogicOperation logicOperation = new LogicOperation();

		if (masc.size() == 1) {
			masc = new MascTransform().shortToLong(masc);
		}
		baseAdress = logicOperation.and(binarryTransformTest.toBinarry(ip),
				binarryTransformTest.toBinarry(masc));
		baseAdressArr = binarryTransformTest.toInteger(baseAdress);

		return baseAdressArr;
	}

	public ArrayList<Integer> getLastAdress(ArrayList<Integer> ip,
			ArrayList<Integer> masc) throws Exception {
		String notOfMasc = "";
		String lastIp = "";
		ArrayList<Integer> lastIpArr = new ArrayList<Integer>();
		BinaryTransform binaryTransformTest = new BinaryTransform();
		LogicOperation logicOperation = new LogicOperation();

		if (masc.size() == 1) {
			masc = new MascTransform().shortToLong(masc);
		}

		notOfMasc = logicOperation.not(binaryTransformTest.toBinarry(masc));
		lastIp = logicOperation.or(notOfMasc, binaryTransformTest.toBinarry(ip));
		lastIpArr = binaryTransformTest.toInteger(lastIp);
		
		return lastIpArr;
	}
	public ArrayList<Integer> getHosts(int nr){
		ArrayList <Integer> arr = new ArrayList<>();
		arr.add((int) Math.pow(2, nr)-2);
		return arr;
	}
	public Map calculateAll(ArrayList<Integer>ip, ArrayList<Integer> mask){
		Map<DictionaryKeys,ArrayList> dictionaryRspValue = new HashMap();
		MascTransform mascTransform = new MascTransform();
		IpClass ipClass = new IpClass();
		try {
			if(mask.size()==1){
				dictionaryRspValue.put(DictionaryKeys.ShortMask, mask);
				dictionaryRspValue.put(DictionaryKeys.LongMask, mascTransform.shortToLong(mask));
				dictionaryRspValue.put(DictionaryKeys.HostNet, getHosts(32 - mask.get(0)));
			}else{
				dictionaryRspValue.put(DictionaryKeys.ShortMask, mascTransform.longToShort(mask));
				dictionaryRspValue.put(DictionaryKeys.LongMask, mask);
				dictionaryRspValue.put(DictionaryKeys.HostNet, getHosts(32 - mascTransform.longToShort(mask).get(0)));
			}
			dictionaryRspValue.put(DictionaryKeys.Address, ip);
			dictionaryRspValue.put(DictionaryKeys.BaseAdress, getBaseAdress(ip, mask));
			dictionaryRspValue.put(DictionaryKeys.Broadcast, getLastAdress(ip, mask));
			dictionaryRspValue.put(DictionaryKeys.Class, ipClass.getIpClass(ip));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, e.getMessage());
			return null;
		}
		return dictionaryRspValue;
	}
}
